<!--
  智慧社区管理系统 - 登录页面
  @author Wu.Liang
  @date 2024-12-21
  @description 按照UI设计文档创建的现代化登录页面，支持响应式布局和动画效果
-->
<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧背景区域 -->
      <div class="login-left">
        <div class="login-bg">
          <div class="bg-placeholder">
            <div class="bg-content">
              <h1 class="system-title">智慧社区管理系统</h1>
              <p class="system-desc">智慧社区管理系统</p>
              <div class="feature-list">
                <div class="feature-item">
                  <el-icon><Monitor /></el-icon>
                  <span>智能监控管理</span>
                </div>
                <div class="feature-item">
                  <el-icon><House /></el-icon>
                  <span>物业服务管理</span>
                </div>
                <div class="feature-item">
                  <el-icon><User /></el-icon>
                  <span>居民生活服务</span>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-overlay"></div>
        </div>
      </div>

      <!-- 右侧登录表单区域 -->
      <div class="login-right">
        <div class="login-form-container">
          <div class="login-header">
            <div class="logo-section">
              <div class="logo-icon">
                <el-icon size="32"><House /></el-icon>
              </div>
              <h2>用户登录</h2>
            </div>
            <p>欢迎使用智慧社区管理系统</p>
          </div>

          <el-form 
            ref="loginFormRef" 
            :model="loginForm" 
            :rules="loginRules" 
            class="login-form"
            @keyup.enter="handleLogin"
            @submit.prevent="handleLogin"
          >
            <!-- 用户名输入框 -->
            <el-form-item prop="username">
              <el-input 
                v-model="loginForm.username" 
                placeholder="请输入用户名" 
                size="large" 
                prefix-icon="User" 
                clearable
                :class="{ 'input-focus': usernameFocused }"
                @focus="usernameFocused = true"
                @blur="usernameFocused = false"
              />
            </el-form-item>

            <!-- 密码输入框 -->
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码" 
                size="large" 
                prefix-icon="Lock"
                show-password 
                clearable
                :class="{ 'input-focus': passwordFocused }"
                @focus="passwordFocused = true"
                @blur="passwordFocused = false"
              />
            </el-form-item>

            <!-- 验证码输入框 -->
            <el-form-item prop="captcha" v-if="captchaEnabled">
              <div class="captcha-container">
                <el-input 
                  v-model="loginForm.captcha" 
                  placeholder="请输入验证码" 
                  size="large" 
                  prefix-icon="Key" 
                  clearable
                  class="captcha-input"
                  :class="{ 'input-focus': captchaFocused }"
                  @focus="captchaFocused = true"
                  @blur="captchaFocused = false"
                />
                <div class="captcha-display" @click="getCaptcha">
                  <div v-if="captchaCode" class="captcha-number">
                    {{ captchaCode }}
                  </div>
                  <div v-else class="captcha-placeholder">
                    <el-icon><Refresh /></el-icon>
                    <span>点击刷新</span>
                  </div>
                </div>
              </div>
            </el-form-item>

            <!-- 记住密码和物业公司注册 -->
            <el-form-item>
              <div class="login-options">
                <el-checkbox v-model="loginForm.rememberMe" class="remember-checkbox">
                  记住密码
                </el-checkbox>
                <div class="login-links">
                  <el-link type="primary" :underline="'never'" @click="forgotPassword">
                    忘记密码？
                  </el-link>
                  <!-- <el-link type="primary" :underline="'never'" @click="registerAccount">
                    注册账号
                  </el-link> -->
                  <el-button 
                    type="success" 
                    size="default" 
                    class="register-btn"
                    @click="goToRegister"
                  >
                    <el-icon><House /></el-icon>
                    物业公司注册
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <!-- 登录按钮 -->
            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                :loading="loading" 
                class="login-btn" 
                @click="handleLogin"
                :disabled="!canLogin"
              >
                <el-icon v-if="loading"><Loading /></el-icon>
                <span>{{ loading ? '登录中...' : '登录' }}</span>
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 其他登录方式 -->
          <div class="other-login">
            <div class="divider">
              <span class="divider-text">其他登录方式</span>
            </div>
            <div class="login-methods">
              <div class="method-item" @click="wechatLogin">
                <el-icon size="24"><ChatDotRound /></el-icon>
                <span>微信登录</span>
              </div>
              <div class="method-item" @click="fingerprintLogin">
                <el-icon size="24"><Key /></el-icon>
                <span>指纹登录</span>
              </div>
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="login-footer">
            <p>&copy; 2024 智慧社区管理系统. 版权所有.</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <el-icon class="loading-icon" size="32"><Loading /></el-icon>
        <p>登录中，请稍候...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 登录页面组件
 * @author Wu.Liang
 * @date 2024-12-21
 * @description 现代化登录页面，支持多种登录方式和响应式设计
 */
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Monitor, 
  House, 
  User, 
  Refresh, 
  Loading, 
  ChatDotRound, 
  Key
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getCaptchaImage } from '@/api/user'
import { usePermissionStore } from '@/store/permission'
import { showError, showSuccess, showInfo } from '@/utils/message'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()
const permissionStore = usePermissionStore()

// 表单引用
const loginFormRef = ref<InstanceType<typeof ElForm>>()

// 加载状态
const loading = ref(false)

// 输入框聚焦状态
const usernameFocused = ref(false)
const passwordFocused = ref(false)
const captchaFocused = ref(false)

// 验证码相关
const captchaEnabled = ref(true)
const captchaCode = ref('')

// 登录表单
const loginForm = reactive({
    username: '',
    password: '',
    captcha: '',
    captchaKey: '',
    rememberMe: false
})

// 表单验证规则
const loginRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 20, message: '密码长度在 5 到 20 个字符', trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{4}$/, message: '请输入4位数字验证码', trigger: 'blur' }
    ]
}

// 计算是否可以登录
const canLogin = computed(() => {
    const hasUsername = loginForm.username.trim().length > 0
    const hasPassword = loginForm.password.trim().length > 0
    const hasCaptcha = !captchaEnabled.value || loginForm.captcha.trim().length === 4
    return hasUsername && hasPassword && hasCaptcha && !loading.value
})

/**
 * 获取4位数字验证码
 */
const getCaptcha = async() => {
    try {
        const response = await getCaptchaImage()
        captchaCode.value = response.data.captcha
        loginForm.captchaKey = response.data.captchaKey
        loginForm.captcha = '' // 清空验证码输入
    } catch (error) {
        console.error('获取验证码失败:', error)
        showError('获取验证码失败，请重试')
    }
}

/**
 * 处理登录
 */
const handleLogin = async() => {
    if (!loginFormRef.value || !canLogin.value) return

    try {
        const valid = await loginFormRef.value.validate()
        if (!valid) return

        loading.value = true

        const loginData = {
            username: loginForm.username.trim(),
            password: loginForm.password,
            captcha: loginForm.captcha,
            captchaKey: loginForm.captchaKey,
            rememberMe: loginForm.rememberMe
        }

        let loadingInstance = null
        try {
            loadingInstance = ElLoading.service({
              lock: true,
              text: '登录中，请稍候...'
            })
            // 登录
            const response = await userStore.login(loginData)
            
            // 等待权限初始化完成，设置超时时间
            await nextTick()
            try {
                await new Promise<void>((resolve, reject) => {
                    const timeout = setTimeout(() => {
                        reject(new Error('权限初始化超时'))
                    }, 3000) // 3秒超时
                    
                    const check = () => {
                        if (permissionStore.menuPermissionCodes.length > 0 || permissionStore.isInitialized) {
                            clearTimeout(timeout)
                            resolve()
                        } else {
                            setTimeout(check, 100)
                        }
                    }
                    check()
                })
            } catch (error) {
                console.warn('权限初始化超时，继续跳转:', error)
            }
            
            // 跳转首页
            router.replace({ path: '/dashboard' })
        } finally {
            loading.value = false
            if (loadingInstance) loadingInstance.close()
        }
    } catch (error) {
        loading.value = false
        ElMessage.error(error.message || '登录失败')
        
        // 登录失败时自动刷新验证码
        if (captchaEnabled.value) {
            await getCaptcha()
        }
    }
}

/**
 * 忘记密码
 */
const forgotPassword = () => {
    showInfo('忘记密码功能开发中...')
}

/**
 * 注册账号
 */
const registerAccount = () => {
    showInfo('注册账号功能开发中...')
}

/**
 * 跳转到物业公司注册页面
 */
const goToRegister = () => {
    router.push('/property/company/register')
}

/**
 * 微信登录
 */
const wechatLogin = () => {
    showInfo('微信登录功能开发中...')
}

/**
 * 指纹登录
 */
const fingerprintLogin = () => {
    showInfo('指纹登录功能开发中...')
}

/**
 * 初始化页面数据
 */
const initPageData = () => {
    // 获取记住的用户名
    const rememberedUsername = userStore.getRememberedUsername()
    if (rememberedUsername) {
        loginForm.username = rememberedUsername
        loginForm.rememberMe = true
    }
    
    // 检查是否已登录
    if (userStore.isLogged) {
        const redirect = router.currentRoute.value.query.redirect as string
        router.push(redirect || '/')
    }
}

// 页面加载时获取验证码和初始化数据
onMounted(async () => {
    initPageData()
    
    if (captchaEnabled.value) {
        await nextTick()
        getCaptcha()
    }
})
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;

  // 背景动画
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
    animation: float 20s ease-in-out infinite;
  }

  .login-wrapper {
    width: 1000px;
    height: 600px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
    display: flex;
    overflow: hidden;
    position: relative;
    z-index: 1;
    animation: slideIn 0.6s ease-out;

    .login-left {
      flex: 1;
      position: relative;

      .login-bg {
        height: 100%;
        position: relative;

        .bg-placeholder {
          width: 100%;
          height: 100%;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;

          .bg-content {
            text-align: center;
            color: white;
            z-index: 2;
            position: relative;

            .system-title {
              font-size: 36px;
              font-weight: bold;
              margin-bottom: 16px;
              text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
              animation: fadeInUp 0.8s ease-out 0.2s both;
            }

            .system-desc {
              font-size: 16px;
              opacity: 0.9;
              margin-bottom: 40px;
              animation: fadeInUp 0.8s ease-out 0.4s both;
            }

            .feature-list {
              .feature-item {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 16px;
                font-size: 14px;
                opacity: 0.8;

                .el-icon {
                  margin-right: 8px;
                  font-size: 16px;
                }

                &:nth-child(1) { animation: fadeInUp 0.8s ease-out 0.6s both; }
                &:nth-child(2) { animation: fadeInUp 0.8s ease-out 0.8s both; }
                &:nth-child(3) { animation: fadeInUp 0.8s ease-out 1.0s both; }
              }
            }
          }
        }

        .bg-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.2);
        }
      }
    }

    .login-right {
      flex: 1;
      padding: 30px 50px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      background: white;

      .login-form-container {
        width: 100%;
        max-width: 350px;
        margin: 0 auto;
        animation: fadeInRight 0.8s ease-out 0.3s both;

        .login-header {
          text-align: center;
          margin-bottom: 30px;

          .logo-section {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;

            .logo-icon {
              width: 48px;
              height: 48px;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              border-radius: 12px;
              display: flex;
              align-items: center;
              justify-content: center;
              color: white;
              margin-right: 12px;
            }

            h2 {
              font-size: 28px;
              color: #333;
              font-weight: 600;
              margin: 0;
            }
          }

          p {
            color: #666;
            font-size: 14px;
            margin: 0;
          }
        }

        .login-form {
          .el-form-item {
            margin-bottom: 20px;

            .el-input {
              .el-input__wrapper {
                border-radius: 8px;
                transition: all 0.3s ease;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

                &:hover {
                  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                }

                &.is-focus {
                  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
                }
              }
            }

            &.input-focus {
              .el-input__wrapper {
                box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
              }
            }
          }

          .captcha-container {
            display: flex;
            gap: 12px;

            .captcha-input {
              flex: 1;
            }

            .captcha-display {
              width: 100px;
              height: 40px;
              border: 1px solid #dcdfe6;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              background: #f5f7fa;
              transition: all 0.3s ease;
              overflow: hidden;

              .captcha-number {
                font-size: 16px;
                font-weight: 600;
                color: #333;
              }

              .captcha-placeholder {
                display: flex;
                flex-direction: column;
                align-items: center;
                font-size: 12px;
                color: #909399;

                .el-icon {
                  margin-bottom: 2px;
                }
              }

              &:hover {
                border-color: #667eea;
                box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
              }
            }
          }

          .login-options {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .remember-checkbox {
              .el-checkbox__label {
                font-size: 14px;
                color: #666;
              }
            }

            .login-links {
              display: flex;
              gap: 16px;
              align-items: center;

              .el-link {
                font-size: 14px;
                transition: all 0.3s ease;

                &:hover {
                  transform: translateY(-1px);
                }
              }

              .register-btn {
                background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
                border: none;
                border-radius: 6px;
                font-weight: 600;
                font-size: 14px;
                padding: 8px 16px;
                box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
                transition: all 0.3s ease;

                &:hover {
                  transform: translateY(-1px);
                  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
                }

                &:active {
                  transform: translateY(0);
                }

                .el-icon {
                  margin-right: 6px;
                  font-size: 14px;
                }
              }
            }
          }

          .login-btn {
            width: 100%;
            height: 44px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover:not(:disabled) {
              transform: translateY(-2px);
              box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
            }

            &:active:not(:disabled) {
              transform: translateY(0);
            }

            &:disabled {
              opacity: 0.6;
              cursor: not-allowed;
            }

            .el-icon {
              margin-right: 8px;
            }
          }
        }

        .other-login {
          margin-top: 12px;

          .divider {
            position: relative;
            text-align: center;
            margin-bottom: 20px;

            &::before {
              content: '';
              position: absolute;
              top: 50%;
              left: 0;
              right: 0;
              height: 1px;
              background: #e8e8e8;
              z-index: 1;
            }

            .divider-text {
              background: white;
              padding: 0 16px;
              color: #999;
              font-size: 12px;
              position: relative;
              z-index: 2;
            }
          }

          .login-methods {
            display: flex;
            justify-content: center;
            gap: 24px;

            .method-item {
              display: flex;
              flex-direction: column;
              align-items: center;
              cursor: pointer;
              padding: 12px;
              border-radius: 8px;
              transition: all 0.3s ease;

              &:hover {
                background: #f5f7fa;
                transform: translateY(-2px);
              }

              .el-icon {
                color: #667eea;
                margin-bottom: 4px;
              }

              span {
                font-size: 12px;
                color: #666;
              }
            }
          }
        }

        .login-footer {
          text-align: center;
          margin-top: 24px;

          p {
            color: #999;
            font-size: 12px;
            margin: 0;
          }
        }
      }
    }
  }

  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;

    .loading-content {
      background: white;
      padding: 32px;
      border-radius: 12px;
      text-align: center;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);

      .loading-icon {
        color: #667eea;
        animation: spin 1s linear infinite;
        margin-bottom: 16px;
      }

      p {
        color: #666;
        margin: 0;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    .login-wrapper {
      width: 90%;
      height: auto;
      min-height: 500px;
      flex-direction: column;

      .login-left {
        height: 200px;
        min-height: 200px;
      }

      .login-right {
        padding: 40px 30px;
        flex: 1;
      }
    }
  }
}

@media (max-width: 480px) {
  .login-container {
    .login-wrapper {
      width: 95%;
      margin: 20px;

      .login-right {
        padding: 30px 20px;
      }
    }
  }
}

// 动画定义
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
